package com.example.partyfee.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.example.partyfee.dto.PartyMemberExcelDTO;
import com.example.partyfee.entity.PartyMember;
import com.example.partyfee.service.PartyMemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class PartyMemberImportListener implements ReadListener<PartyMemberExcelDTO> {

    private static final int BATCH_COUNT = 100;
    private List<PartyMember> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private final PartyMemberService partyMemberService;
    private final List<String> errorMessages = new ArrayList<>();

    public PartyMemberImportListener(PartyMemberService partyMemberService) {
        this.partyMemberService = partyMemberService;
    }

    @Override
    public void invoke(PartyMemberExcelDTO data, AnalysisContext context) {
        PartyMember partyMember = new PartyMember();
        try {
            BeanUtils.copyProperties(data, partyMember);
            cachedDataList.add(partyMember);
            if (cachedDataList.size() >= BATCH_COUNT) {
                saveData();
                cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
            }
        } catch (Exception e) {
            log.error("解析Excel数据失败: {}", e.getMessage());
            errorMessages.add(String.format("第%d行数据解析失败: %s", context.readRowHolder().getRowIndex() + 1, e.getMessage()));
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData() {
        if (!cachedDataList.isEmpty()) {
            try {
                partyMemberService.batchSavePartyMembers(cachedDataList);
            } catch (Exception e) {
                log.error("保存党员数据失败: {}", e.getMessage());
                errorMessages.add("批量保存数据失败: " + e.getMessage());
            }
        }
    }

    public List<String> getErrorMessages() {
        return errorMessages;
    }

    public boolean hasErrors() {
        return !errorMessages.isEmpty();
    }
} 